package com.xy.servicemanage.request;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.xy.core.util.SpringBeanUtils;
import com.xy.manage.model.Tservicelog;
import com.xy.manage.service.TservicelogService;
import com.xy.servicemanage.model.ServiceSetting;
import com.xy.servicemanage.model.Tservices;

public class LoggerUtils {
	static ExecutorService pool = Executors.newFixedThreadPool(20);
	public static TservicelogService tservicelogService =((TservicelogService) SpringBeanUtils
			.getBean("tservicelogService"));

	public static void log(final Map value) {
		pool.execute(new Runnable() {
			@Override
			public void run() {
				try {
					doLog(value);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}

	private static void doLog(Map value) {

		String sid = (String) value.get("CLWID");

		Tservices tservices = ServiceSetting.getInstance()
				.getServiceByServiceId(sid);
		if (tservices.getIsLog() == null || !"1".equals(tservices.getIsLog()))
			return;
		String logPattern = tservices.getLogPattern();
		String phoneNo = (String) value.get("phoneID");
		String sourceip = (String) value.get("sourceip");
		String loginfo = parse(logPattern, value);

		Tservicelog tservicelog = new Tservicelog();
		tservicelog.setInvokedate(new Date());
		tservicelog.setSid(Long.parseLong(sid));
		tservicelog.setSourceip(sourceip);
		tservicelog.setPhoneNo(phoneNo);
		tservicelog.setLoginfo(loginfo);
		tservicelogService.save(tservicelog);

	}

	private static String parse(String logPattern, Map value) {
		// 机动车状态查询 logPattern: 号牌号码:{HPHM},发动机号:{FDJH}
		// 处理后应该是：号牌号码:11223,发动机号:3333
        String tmp=logPattern;
		String regEx = "\\{\\w+\\}";
		
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(logPattern);
		List<String> l = new ArrayList<String>();
		while(mat.find()){
			String k=mat.group();
			String k1=k.substring(1);
			String k2=k1.substring(0,k1.length()-1);
			
			l.add(k2);
		}
		Map<String, String> m = new HashMap<String, String>();
		for (String k : l) {
			String v=(String)value.get(k);
			if(v==null)v="";
			m.put(k, v);
		}
		Set<String> set = m.keySet();
		for (String k : set) {
			String v = m.get(k);
			tmp=tmp.replaceAll("\\{"+k+"\\}", v);
		}
		return tmp;
	}
public static void main(String args[]){
	Map<String,String> m=new HashMap<String, String>();
	m.put("a1", "sdfaf");
	m.put("a2", "ewr23");
	String s="name:{a1},code:{a2}";
	System.out.println(parse(s, m));
}
}
